package com.zz.tijian.service.impl;


import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zz.tijian.entity.Hospital;
import com.zz.tijian.entity.doc.HospitalDoc;
import com.zz.tijian.entity.req.HosRequestDto;
import com.zz.tijian.entity.res.Result;
import com.zz.tijian.mapper.HospitalMapper;
import com.zz.tijian.service.CheckitemService;
import com.zz.tijian.service.HospitalService;
import com.zz.tijian.service.SetmealdetailedService;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.functionscore.FunctionScoreQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
* @author 17958
* @description 针对表【hospital】的数据库操作Service实现
* @createDate 2024-06-13 12:05:47
*/
@Service
public class HospitalServiceImpl extends ServiceImpl<HospitalMapper, Hospital>
    implements HospitalService {

    @Autowired
    private SetmealdetailedService setmealdetailedService;
    @Autowired
    private CheckitemService checkitemService;
    @Autowired
    private RestHighLevelClient client;

    @Override
    public Result<List<Hospital>> getAll() {
        //查询所有套餐
        List<Hospital> result = this.list();
        
        return Result.ok(result);
    }

    @Override
    public Result<List<Hospital>> search(HosRequestDto params) {
        try {
            // 1.准备request
            SearchRequest searchRequest=new SearchRequest("hospital");
            // 2.准备DSL
            // 2.1 query
            buildBasicQuery(params,searchRequest);

            // 3.发送请求
            SearchResponse response = client.search(searchRequest, RequestOptions.DEFAULT);
            // 4.解析响应
            return handleResponse(response);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    private static void buildBasicQuery(HosRequestDto params,SearchRequest searchRequest) {

        // 构建BooleanQuery
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        // must 关键字搜索
        String key = params.getKey();
        if(key == null || key.trim().length() == 0){
            boolQueryBuilder.must(QueryBuilders.matchAllQuery());
        }else {
            boolQueryBuilder.must(QueryBuilders.matchQuery("all",key));
        }
        // 起始营业时间条件
        if(params.getStartTime() != null && params.getStartTime().trim().length() > 0){
            boolQueryBuilder.filter(QueryBuilders.rangeQuery("startTime").gte( params.getStartTime()));
        }
        // 结束营业时间条件
        if(params.getEndTime() != null && params.getEndTime().trim().length() > 0){
            boolQueryBuilder.filter(QueryBuilders.rangeQuery("endTime").lte( params.getEndTime()));
        }
        // 采血结束时间条件
        if(params.getDeadlineTime() != null && params.getDeadlineTime().trim().length() > 0){
            boolQueryBuilder.filter(QueryBuilders.rangeQuery("deadlineTime").lte( params.getDeadlineTime()));
        }

        // 2.算分控制
        FunctionScoreQueryBuilder functionScoreQuery =
                QueryBuilders.functionScoreQuery(
                        // 原始查询，相关性算分的查询
                        boolQueryBuilder);
        searchRequest.source().query(functionScoreQuery);
    }

    private static Result<List<Hospital>> handleResponse(SearchResponse response) {
        // 4.解析响应
        SearchHits searchHits = response.getHits();
        // 4.1获取总条数
        long total = searchHits.getTotalHits().value;
        System.out.println("总共搜索到:"+total+"条数据");
        // 4.2文档数组
        SearchHit[] hits = searchHits.getHits();
        // 4.3遍历
        List<Hospital> list = new ArrayList<>();
        for (SearchHit hit : hits) {
            String json = hit.getSourceAsString();
            HospitalDoc hospitalDoc = JSON.parseObject(json, HospitalDoc.class);
            Hospital hospital = new Hospital();
            BeanUtils.copyProperties(hospitalDoc,hospital);
            list.add(hospital);
        }
        // 4.4 封装返回
        return Result.ok(list);
    }

}




